<template>
  <div style="margin-top: 150px">
    <el-row>
      <el-col :span="12" :offset="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>科泰购后台登录</span>
          </div>
          <el-form
            ref="myForm"
            :rules="rules"
            :model="form.user"
            label-width="80px"
          >
            <el-form-item label="用户名" prop="loginName">
              <el-input v-model="form.user.loginName"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="form.user.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">登录</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 引用 qs 插件用于处理表单数据
import qs from "qs";
export default {
  data() {
    //rule:验证规则   value:当前验证项的值  callback:回调函数
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码!!!"));
      } else {
        callback();
      }
    };
    return {
      form: {
        opr: "login",
        user: {
          loginName: "",
          password: "",
        },
      },
      rules: {
        loginName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        /* password: [{ required: true, message: "请输入密码", trigger: "blur" }], */
        password: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm() {
      this.$refs.myForm.validate((valid) => {
        if (valid) {
          console.log("准备提交后端请求");
          // 使用 qs 插件转换对象数据为查询字符串
          let bodyData = qs.parse(qs.stringify(this.form));
          //  发送登录请求
          this.$axios.post("/uni/manager/user", bodyData).then((res) => {
            console.log("返回值", res);
            if (res.data.code === 200) {
              //  登录的用户数据保存在 data  中
              let userInfo = res.data.result;
              //  登录成功
              this.$message.success(res.data.msg);
              this.$store.commit("login", userInfo);
              //  编程式路由跳转到/main
              this.$router.push({ path: "/main" });
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          this.$message.error("客户端验证失败,请输入用户名和密码");
        }
      });
    },
    resetForm() {
      this.$refs.myForm.resetFields();
    },
  },
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
